#include "devicemanagement.h"
#include "core/databasepool/databasepool.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>

// 获取最后一次操作的错误信息
QString DeviceManagement::getLastError() const
{
    return m_lastError;
}

// 创建设备表
void DeviceManagement::createDeviceTable()
{
    QMutexLocker locker(&m_mutex);
    QSqlDatabase db = DatabasePool::instance().getConnection();
    QSqlQuery query(db);
    // 使用 CREATE TABLE IF NOT EXISTS 避免表已存在时出错
    if (!query.exec(R"(
                    CREATE TABLE IF NOT EXISTS devices (
                    device_id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL,
                    type TEXT NOT NULL,
                    location TEXT NOT NULL,
                    manufacturer TEXT,
                    model TEXT,
                    status TEXT DEFAULT '正常',
                    installation_date TEXT
                    )
                    )")) {
        m_lastError = query.lastError().text();
        qDebug() << "devices创建表失败: " << m_lastError;
    }
    DatabasePool::instance().releaseConnection(db);
}


// 构造函数
DeviceManagement::DeviceManagement(QObject *parent) : QObject(parent)
{
    createDeviceTable();
}

// 析构函数
DeviceManagement::~DeviceManagement()
{
    // 无需释放连接，因为每个方法中已经动态管理连接
}

// 添加设备
bool DeviceManagement::addDevice(const QString& name, const QString& type, const QString& location,
                                 const QString& manufacturer, const QString& model, const QString& installationDate)
{
    QMutexLocker locker(&m_mutex);
    QSqlDatabase db = DatabasePool::instance().getConnection();
    QSqlQuery insertQuery(db);
    insertQuery.prepare("INSERT INTO devices (name, type, location, manufacturer, model, installation_date) "
                        "VALUES (:name, :type, :location, :manufacturer, :model, :date)");
    insertQuery.bindValue(":name", name);
    insertQuery.bindValue(":type", type);
    insertQuery.bindValue(":location", location);
    insertQuery.bindValue(":manufacturer", manufacturer);
    insertQuery.bindValue(":model", model);
    insertQuery.bindValue(":date", installationDate);

    // 执行插入操作
    bool success = insertQuery.exec();
    if (!success) {
        qDebug() << "插入设备数据失败: " << insertQuery.lastError().text();
        m_lastError = insertQuery.lastError().text();
    }
    DatabasePool::instance().releaseConnection(db);
    return success;
}

// 删除设备
bool DeviceManagement::deleteDevice(int deviceId)
{
    QMutexLocker locker(&m_mutex);
    QSqlDatabase db = DatabasePool::instance().getConnection();
    QSqlQuery query(db);
    query.prepare("DELETE FROM devices WHERE device_id = :device_id");
    query.bindValue(":device_id", deviceId);

    bool success = query.exec();
    if (!success) {
        qDebug() << "删除设备数据失败: " << query.lastError().text();
        m_lastError = query.lastError().text();
    }
    DatabasePool::instance().releaseConnection(db);
    return success;
}

// 修改设备信息
bool DeviceManagement::updateDevice(int deviceId, const QString& name, const QString& type, const QString& status)
{
    QMutexLocker locker(&m_mutex);
    QSqlDatabase db = DatabasePool::instance().getConnection();
    QSqlQuery query(db);
    query.prepare("UPDATE devices SET name = :name, type = :type, status = :status WHERE device_id = :device_id");
    query.bindValue(":device_id", deviceId);
    query.bindValue(":name", name);
    query.bindValue(":type", type);
    query.bindValue(":status", status);

    bool success = query.exec();
    if (!success) {
        qDebug() << "更新设备数据失败: " << query.lastError().text();
        m_lastError = query.lastError().text();
    }
    DatabasePool::instance().releaseConnection(db);
    return success;
}

QList<QSqlRecord> DeviceManagement::getDevicesByType(const QString& type)
{
    QMutexLocker locker(&m_mutex);
    QList<QSqlRecord> records;
    QSqlDatabase db = DatabasePool::instance().getConnection();
    QSqlQuery query(db);

    query.prepare("SELECT * FROM devices WHERE type = :type");
    query.bindValue(":type", type);

    if (query.exec()) {
        while (query.next()) {
            records.append(query.record());
        }
    } else {
        qDebug() << "按类型查询设备数据失败: " << query.lastError().text();
        m_lastError = query.lastError().text();
    }
    DatabasePool::instance().releaseConnection(db);
    return records;
}

QList<QSqlRecord> DeviceManagement::getDevicesByLocation(const QString& location)
{
    QMutexLocker locker(&m_mutex);
    QList<QSqlRecord> records;
    QSqlDatabase db = DatabasePool::instance().getConnection();
    QSqlQuery query(db);

    query.prepare("SELECT * FROM devices WHERE location = :location");
    query.bindValue(":location", location);

    if (query.exec()) {
        while (query.next()) {
            records.append(query.record());
        }
    } else {
        qDebug() << "按位置查询设备数据失败: " << query.lastError().text();
        m_lastError = query.lastError().text();
    }
    DatabasePool::instance().releaseConnection(db);
    return records;
}

// DeviceManagement::deviceExists
bool DeviceManagement::deviceExists(int deviceId)
{
    QMutexLocker locker(&m_mutex);
    QSqlDatabase db = DatabasePool::instance().getConnection();
    QSqlQuery query(db);
    query.prepare("SELECT 1 FROM devices WHERE device_id = :device_id");
    query.bindValue(":device_id", deviceId);

    bool exists = query.exec() && query.next();
    DatabasePool::instance().releaseConnection(db);
    return exists;
}
